﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MyConsoleTraceListener.cs" company="">
//   
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ExecutionTool.Common
{
    using System;
    using System.Diagnostics;

    using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging;
    using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;

    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class MyConsoleTraceListener : CustomTraceListener
    {
        #region Public Properties

        public override bool IsThreadSafe
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region Public Methods and Operators

        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            var entLibLogEntry = data as LogEntry;

            if (entLibLogEntry == null)
            {
                base.TraceData(eventCache, source, eventType, id, data);
                return;
            }

            Console.Write("[{0}] ", entLibLogEntry.TimeStamp);
            var color = Console.ForegroundColor;
            Console.ForegroundColor = GetNewColor(entLibLogEntry.Severity);
            Console.Write("[{0}] ", entLibLogEntry.Severity);
            Console.ForegroundColor = color;
            Console.Write("{0}\r\n", entLibLogEntry.Message);
        }

        public override void Write(string message)
        {
            throw new NotImplementedException();
        }

        public override void WriteLine(string message)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Methods

        private static ConsoleColor GetNewColor(TraceEventType severity)
        {
            switch (severity)
            {
                case TraceEventType.Information:
                    return ConsoleColor.Green;
                case TraceEventType.Verbose:
                    return ConsoleColor.Blue;
                case TraceEventType.Warning:
                    return ConsoleColor.Yellow;
                case TraceEventType.Error:
                    return ConsoleColor.Red;
                default:
                    return Console.ForegroundColor;
            }
        }

        #endregion
    }
}
